<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>主管仪表板 - OpenOKR</title>
    <meta name="page-title" content="dashboard.manager">
    <link rel="stylesheet" href="/static/css/style.css">
    <script src="/static/js/i18n.js"></script>
</head>
<body>
    <nav class="navbar">
        <a href="/" class="navbar-brand" style="display: flex; align-items: center; gap: 0.5rem;">
            <img src="/static/images/openokr.png" alt="OpenOKR" style="height: 32px; width: auto;">
            <span data-i18n="app.name">OpenOKR</span>
        </a>
        <ul class="navbar-menu">
            <li><a href="/auth/dashboard" data-i18n="nav.dashboard">仪表板</a></li>
            <li>
                <select id="language-selector" onchange="switchLanguage(this.value)" style="background: transparent; border: 1px solid rgba(255,255,255,0.3); color: white; padding: 0.3rem 0.5rem; border-radius: 4px; cursor: pointer;">
                    <option value="zh">中文</option>
                    <option value="en">English</option>
                </select>
            </li>
            <li><a href="#" onclick="logout()" data-i18n="nav.logout">登出</a></li>
        </ul>
    </nav>

    <div class="container-fluid">
        <h1 style="margin-bottom: 2rem;" data-i18n="dashboard.manager">主管仪表板</h1>

        <!-- 第一部分：部门目标 -->
        <div class="card">
            <div class="card-header">
                🎯 <span data-i18n="objective.department">部门目标</span>
                <button onclick="openModal('create-objective-modal')" class="btn btn-primary" style="float: right;" data-i18n="objective.create">创建目标</button>
            </div>
            <div class="card-body">
                <div id="objectives-by-type">
                    <p style="text-align: center; color: var(--text-secondary);" data-i18n="common.loading">加载中...</p>
                </div>
            </div>
        </div>

        <!-- 第二部分：当前项目 -->
        <div class="card">
            <div class="card-header">
                📁 <span data-i18n="project.title">当前项目</span>
                <button onclick="openCreateProjectModal()" class="btn btn-primary" style="float: right;" data-i18n="project.create">创建项目</button>
            </div>
            <div class="card-body">
                <div class="grid grid-3" id="projects-container">
                    <p style="text-align: center; color: var(--text-secondary);" data-i18n="common.loading">加载中...</p>
                </div>
            </div>
        </div>

        <!-- 第三部分：下属团队 -->
        <div class="card">
            <div class="card-header">👥 <span data-i18n="team.subordinates">下属团队</span></div>
            <div class="card-body">
                <div class="grid grid-4" id="subordinates-container">
                    <p style="text-align: center; color: var(--text-secondary);" data-i18n="common.loading">加载中...</p>
                </div>
            </div>
        </div>

        <!-- 智能查询小窗口 -->
        <div class="card">
            <div class="card-header">🤖 <span data-i18n="ai.query">AI智能查询</span></div>
            <div class="card-body">
                <div class="form-group">
                    <input type="text" id="ai-query-input" class="form-input"
                           data-i18n-placeholder="ai.placeholder"
                           placeholder="输入问题，例如：团队目标完成情况如何？">
                </div>
                <button onclick="performAIQuery()" class="btn btn-primary" data-i18n="ai.send">查询</button>
                <div id="ai-response" style="margin-top: 1rem; display: none;">
                    <div class="card" style="background: linear-gradient(135deg, #f8fafc 0%, #e0f2fe 100%); border-left: 4px solid var(--primary-color);">
                        <div id="ai-response-text" style="line-height: 1.8;"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 创建目标模态框 -->
    <div id="create-objective-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">创建新目标</div>
            <form id="create-objective-form">
                <div class="form-group">
                    <label class="form-label">目标标题</label>
                    <input type="text" name="title" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">描述</label>
                    <textarea name="description" class="form-textarea"></textarea>
                </div>
                <div class="grid grid-2">
                    <div class="form-group">
                        <label class="form-label">级别</label>
                        <select name="level" class="form-select" required>
                            <option value="department">部门级</option>
                            <option value="individual">个人级</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">类型</label>
                        <select name="type" class="form-select" required>
                            <option value="operational">经营目标</option>
                            <option value="strategic">战略目标</option>
                            <option value="development">研发目标</option>
                        </select>
                    </div>
                </div>
                <div class="grid grid-2">
                    <div class="form-group">
                        <label class="form-label">开始日期</label>
                        <input type="date" name="start_date" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">结束日期</label>
                        <input type="date" name="end_date" class="form-input" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" onclick="closeModal('create-objective-modal')" class="btn btn-secondary">取消</button>
                    <button type="submit" class="btn btn-primary">创建</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑目标模态框 -->
    <div id="edit-objective-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">编辑目标</div>
            <form id="edit-objective-form">
                <input type="hidden" id="edit-objective-id">
                <div class="form-group">
                    <label class="form-label">目标标题</label>
                    <input type="text" name="title" id="edit-objective-title" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">描述</label>
                    <textarea name="description" id="edit-objective-description" class="form-textarea"></textarea>
                </div>
                <div class="grid grid-2">
                    <div class="form-group">
                        <label class="form-label">类型</label>
                        <select name="type" id="edit-objective-type" class="form-select" required>
                            <option value="operational">经营目标</option>
                            <option value="strategic">战略目标</option>
                            <option value="development">研发目标</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">状态</label>
                        <select name="status" id="edit-objective-status" class="form-select" required>
                            <option value="active">进行中</option>
                            <option value="completed">已完成</option>
                            <option value="cancelled">已取消</option>
                        </select>
                    </div>
                </div>
                <div class="grid grid-2">
                    <div class="form-group">
                        <label class="form-label">开始日期</label>
                        <input type="date" name="start_date" id="edit-objective-start-date" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">结束日期</label>
                        <input type="date" name="end_date" id="edit-objective-end-date" class="form-input" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" onclick="closeModal('edit-objective-modal')" class="btn btn-secondary">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 创建项目模态框 -->
    <div id="create-project-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">创建新项目</div>
            <form id="create-project-form">
                <div class="form-group">
                    <label class="form-label">项目名称 *</label>
                    <input type="text" name="name" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">项目描述</label>
                    <textarea name="description" class="form-textarea"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">关联目标 *</label>
                    <select name="objective_id" id="create-project-objective-select" class="form-select" required>
                        <option value="">选择此项目服务的目标</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">负责人 *</label>
                    <select name="owner_id" id="create-project-owner-select" class="form-select" required>
                        <option value="">选择项目负责人</option>
                    </select>
                </div>
                <div class="grid grid-2">
                    <div class="form-group">
                        <label class="form-label">开始日期 *</label>
                        <input type="date" name="start_date" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">结束日期</label>
                        <input type="date" name="end_date" class="form-input">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" onclick="closeModal('create-project-modal')" class="btn btn-secondary">取消</button>
                    <button type="submit" class="btn btn-primary">创建</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑项目模态框 -->
    <div id="edit-project-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">编辑项目</div>
            <form id="edit-project-form">
                <input type="hidden" id="edit-project-id">
                <input type="hidden" id="edit-project-old-objective-id">
                <div class="form-group">
                    <label class="form-label">项目名称 *</label>
                    <input type="text" name="name" id="edit-project-name" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">项目描述</label>
                    <textarea name="description" id="edit-project-description" class="form-textarea"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">关联目标 *</label>
                    <select name="objective_id" id="edit-project-objective-select" class="form-select" required>
                        <option value="">选择此项目服务的目标</option>
                    </select>
                    <small style="color: var(--text-secondary); font-size: 0.875rem;">可以重新选择项目关联的目标</small>
                </div>
                <div class="form-group">
                    <label class="form-label">负责人 *</label>
                    <select name="owner_id" id="edit-project-owner-select" class="form-select" required>
                        <option value="">选择项目负责人</option>
                    </select>
                </div>
                <div class="grid grid-2">
                    <div class="form-group">
                        <label class="form-label">开始日期 *</label>
                        <input type="date" name="start_date" id="edit-project-start-date" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">结束日期</label>
                        <input type="date" name="end_date" id="edit-project-end-date" class="form-input">
                    </div>
                </div>
                <div class="grid grid-2">
                    <div class="form-group">
                        <label class="form-label">进度 (%)</label>
                        <input type="number" name="progress" id="edit-project-progress" class="form-input" min="0" max="100" step="1">
                    </div>
                    <div class="form-group">
                        <label class="form-label">状态</label>
                        <select name="status" id="edit-project-status" class="form-select">
                            <option value="active">进行中</option>
                            <option value="completed">已完成</option>
                            <option value="on_hold">暂停</option>
                            <option value="cancelled">已取消</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" onclick="confirmDeleteProject()" class="btn btn-danger" style="margin-right: auto;">删除项目</button>
                    <button type="button" onclick="closeModal('edit-project-modal')" class="btn btn-secondary">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script src="/static/js/common.js"></script>
    <script>
        let allSubordinates = []; // 存储所有下属信息
        let allProjects = []; // 存储所有项目信息

        // 加载部门目标（只显示部门级别的目标，可点击展开查看下属的个人目标和关联项目）
        async function loadObjectivesByType() {
            try {
                const allObjectives = await getObjectives();
                const container = document.getElementById('objectives-by-type');

                // 只获取部门级别的目标
                const departmentObjectives = allObjectives.filter(obj => obj.level === 'department');

                if (departmentObjectives.length === 0) {
                    container.innerHTML = '<p style="text-align: center; color: var(--text-secondary);">暂无部门目标</p>';
                    return;
                }

                // 按类型分组
                const byType = {
                    operational: [],
                    strategic: [],
                    development: []
                };

                departmentObjectives.forEach(obj => {
                    if (byType[obj.type]) {
                        byType[obj.type].push(obj);
                    }
                });

                const typeLabels = {
                    operational: getTypeLabel('operational'),
                    strategic: getTypeLabel('strategic'),
                    development: getTypeLabel('development')
                };

                const html = Object.keys(byType).map(type => {
                    const objs = byType[type];
                    if (objs.length === 0) return '';

                    const content = objs.map(obj => {
                        // 找到该目标的下属个人目标
                        const childObjectives = allObjectives.filter(o => o.parent_id === obj.id);

                        // 找到该目标关联的项目
                        const relatedProjects = allProjects.filter(proj =>
                            proj.linked_objectives && proj.linked_objectives.some(link => link.objective_id === obj.id)
                        );

                        return `<div style="margin-bottom: 0.75rem; border: 1px solid var(--border-color); padding: 0.75rem; border-radius: 6px;">
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <div style="flex: 1; ${(childObjectives.length > 0 || relatedProjects.length > 0) ? 'cursor: pointer;' : ''}" ${(childObjectives.length > 0 || relatedProjects.length > 0) ? `onclick="toggleChildObjectives(${obj.id})"` : ''}>
                                    <div style="font-weight: 500; color: var(--text-primary);">
                                        ${obj.title}
                                        ${childObjectives.length > 0 ? `<span style="font-size: 0.75rem; color: var(--text-secondary);"> · ${childObjectives.length} ${t('objective.subordinates')}</span>` : ''}
                                        ${relatedProjects.length > 0 ? `<span style="font-size: 0.75rem; color: var(--text-secondary);"> · ${relatedProjects.length} ${t('objective.projects')}</span>` : ''}
                                    </div>
                                    <div style="font-size: 0.875rem; color: var(--text-secondary); margin-top: 0.25rem;">
                                        ${obj.description || '暂无描述'}
                                    </div>
                                </div>
                                <div style="display: flex; align-items: center; gap: 0.5rem;">
                                    <button onclick="event.stopPropagation(); openEditObjective(${obj.id})" class="btn btn-sm btn-secondary" style="padding: 0.25rem 0.5rem; font-size: 0.75rem;">${t('common.edit')}</button>
                                    <button onclick="event.stopPropagation(); confirmDeleteObjective(${obj.id})" class="btn btn-sm btn-danger" style="padding: 0.25rem 0.5rem; font-size: 0.75rem;">${t('common.delete')}</button>
                                    ${(childObjectives.length > 0 || relatedProjects.length > 0) ? `
                                        <span id="toggle-icon-${obj.id}" style="font-size: 1.2rem; color: var(--text-secondary); user-select: none; cursor: pointer;" onclick="toggleChildObjectives(${obj.id})">
                                            ▼
                                        </span>
                                    ` : ''}
                                </div>
                            </div>
                            <div style="margin-top: 0.5rem;" onclick="event.stopPropagation()">
                                <div class="progress">
                                    <div class="progress-bar ${obj.progress >= 70 ? 'success' : obj.progress >= 40 ? 'warning' : 'danger'}"
                                         style="width: ${obj.progress}%"></div>
                                </div>
                                <span style="font-size: 0.75rem; color: var(--text-secondary);">${obj.progress}%</span>
                            </div>
                            <div id="child-objectives-${obj.id}" style="display: none; margin-top: 1rem; padding-top: 1rem; border-top: 1px solid var(--border-color);" onclick="event.stopPropagation()">
                                ${childObjectives.length > 0 ? `
                                    <div style="font-weight: 600; font-size: 0.875rem; color: var(--text-primary); margin-bottom: 0.5rem;">${t('objective.subordinate_list')}</div>
                                    ${childObjectives.map(child => `
                                        <div style="padding: 0.5rem; background: var(--background-color); border-radius: 4px; margin-bottom: 0.5rem;">
                                            <div style="font-size: 0.875rem; font-weight: 500;">👤 ${child.owner_name}: ${child.title}</div>
                                            <div style="margin-top: 0.25rem;">
                                                <div class="progress" style="height: 4px;">
                                                    <div class="progress-bar ${child.progress >= 70 ? 'success' : child.progress >= 40 ? 'warning' : 'danger'}"
                                                         style="width: ${child.progress}%"></div>
                                                </div>
                                                <span style="font-size: 0.7rem; color: var(--text-secondary);">${child.progress}%</span>
                                            </div>
                                        </div>
                                    `).join('')}
                                ` : ''}
                                ${relatedProjects.length > 0 ? `
                                    <div style="font-weight: 600; font-size: 0.875rem; color: var(--text-primary); margin-top: ${childObjectives.length > 0 ? '1rem' : '0'}; margin-bottom: 0.5rem;">${t('objective.project_list')}</div>
                                    ${relatedProjects.map(proj => `
                                        <div style="padding: 0.5rem; background: var(--background-color); border-radius: 4px; margin-bottom: 0.5rem; cursor: pointer;" onclick="event.stopPropagation(); openEditProject(${proj.id})">
                                            <div style="font-size: 0.875rem; font-weight: 500;">📦 ${proj.name} <span style="color: var(--text-secondary); font-weight: normal;">${t('project.owner')}: ${proj.owner?.full_name || t('project.unassigned')}</span></div>
                                            <div style="margin-top: 0.25rem;">
                                                <div class="progress" style="height: 4px;">
                                                    <div class="progress-bar ${proj.progress >= 70 ? 'success' : proj.progress >= 40 ? 'warning' : 'danger'}"
                                                         style="width: ${proj.progress}%"></div>
                                                </div>
                                                <span style="font-size: 0.7rem; color: var(--text-secondary);">${proj.progress}% · ${getStatusBadge(proj.status)}</span>
                                            </div>
                                        </div>
                                    `).join('')}
                                ` : ''}
                            </div>
                        </div>`;
                    }).join('');

                    return `
                        <div style="margin-bottom: 2rem;">
                            <h3 style="font-size: 1.125rem; font-weight: 600; margin-bottom: 1rem; color: var(--primary-color);">
                                ${typeLabels[type]}
                            </h3>
                            ${content}
                        </div>
                    `;
                }).filter(h => h).join('');

                container.innerHTML = html || '<p style="text-align: center; color: var(--text-secondary);">暂无目标</p>';
            } catch (error) {
                showNotification('加载目标失败', 'error');
            }
        }

        // 切换显示下属目标
        function toggleChildObjectives(objectiveId) {
            const element = document.getElementById(`child-objectives-${objectiveId}`);
            const icon = document.getElementById(`toggle-icon-${objectiveId}`);
            if (element.style.display === 'none') {
                element.style.display = 'block';
                if (icon) icon.textContent = '▲';
            } else {
                element.style.display = 'none';
                if (icon) icon.textContent = '▼';
            }
        }

        // 加载项目卡片（按目标分组）
        async function loadProjects() {
            try {
                const projects = await getProjects({ include_objectives: true });
                const container = document.getElementById('projects-container');

                if (projects.length === 0) {
                    container.innerHTML = '<p style="text-align: center; color: var(--text-secondary); grid-column: 1 / -1;">暂无项目</p>';
                    return;
                }

                // 按目标分组
                const projectsByObjective = {};
                const unlinkedProjects = [];

                projects.forEach(proj => {
                    if (proj.linked_objectives && proj.linked_objectives.length > 0) {
                        proj.linked_objectives.forEach(link => {
                            const objId = link.objective_id;
                            if (!projectsByObjective[objId]) {
                                projectsByObjective[objId] = {
                                    objective: link.objective,
                                    projects: []
                                };
                            }
                            projectsByObjective[objId].projects.push(proj);
                        });
                    } else {
                        unlinkedProjects.push(proj);
                    }
                });

                // 按目标类型排序（经营>战略>研发）
                const typeOrder = { operational: 1, strategic: 2, development: 3 };
                const sortedGroups = Object.values(projectsByObjective).sort((a, b) => {
                    return (typeOrder[a.objective.type] || 999) - (typeOrder[b.objective.type] || 999);
                });

                let html = '<div style="grid-column: 1 / -1;">';

                // 按排序后的目标分组显示
                sortedGroups.forEach(group => {
                    const obj = group.objective;
                    const typeLabels = {
                        operational: '经营',
                        strategic: '战略',
                        development: '研发'
                    };
                    const typeLabel = typeLabels[obj.type] || obj.type;

                    html += `
                        <div style="margin-bottom: 1.5rem;">
                            <div style="font-weight: 600; margin-bottom: 0.75rem; color: var(--primary-color); font-size: 0.95rem;">
                                🎯 [${typeLabel}] ${obj.title} (${group.projects.length}个项目)
                            </div>
                            <div class="grid grid-3" style="margin-left: 1rem;">
                                ${group.projects.map(proj => `
                                    <div class="card" style="padding: 1rem; cursor: pointer;" onclick="event.stopPropagation(); openEditProject(${proj.id})">
                                        <h4 style="margin-bottom: 0.5rem; font-size: 0.95rem;">${proj.name}</h4>
                                        <p style="font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 0.75rem;">
                                            ${proj.description || '暂无描述'}
                                        </p>
                                        <div style="margin-bottom: 0.5rem;">
                                            <div class="progress" style="height: 6px;">
                                                <div class="progress-bar ${proj.progress >= 70 ? 'success' : proj.progress >= 40 ? 'warning' : 'danger'}"
                                                     style="width: ${proj.progress}%"></div>
                                            </div>
                                            <span style="font-size: 0.75rem; color: var(--text-secondary);">${proj.progress}%</span>
                                        </div>
                                        <div style="margin-top: 0.5rem; display: flex; justify-content: space-between; align-items: center;">
                                            ${getStatusBadge(proj.status)}
                                            <span style="font-size: 0.75rem; color: var(--text-secondary);">
                                                👤 ${proj.owner?.full_name || '未分配'}
                                            </span>
                                        </div>
                                        <div style="margin-top: 0.5rem; font-size: 0.75rem; color: var(--text-secondary);">
                                            📅 ${formatDate(proj.start_date)} - ${formatDate(proj.end_date)}
                                        </div>
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    `;
                });

                // 未关联的项目
                if (unlinkedProjects.length > 0) {
                    html += `
                        <div style="margin-bottom: 1.5rem;">
                            <div style="font-weight: 600; margin-bottom: 0.75rem; color: var(--secondary-color); font-size: 0.95rem;">
                                📋 未关联目标的项目
                            </div>
                            <div class="grid grid-3" style="margin-left: 1rem;">
                                ${unlinkedProjects.map(proj => `
                                    <div class="card" style="padding: 1rem; cursor: pointer;" onclick="event.stopPropagation(); openEditProject(${proj.id})">
                                        <h4 style="margin-bottom: 0.5rem; font-size: 0.95rem;">${proj.name}</h4>
                                        <p style="font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 0.75rem;">
                                            ${proj.description || '暂无描述'}
                                        </p>
                                        <div style="margin-bottom: 0.5rem;">
                                            <div class="progress" style="height: 6px;">
                                                <div class="progress-bar ${proj.progress >= 70 ? 'success' : proj.progress >= 40 ? 'warning' : 'danger'}"
                                                     style="width: ${proj.progress}%"></div>
                                            </div>
                                            <span style="font-size: 0.75rem; color: var(--text-secondary);">${proj.progress}%</span>
                                        </div>
                                        <div style="margin-top: 0.5rem;">
                                            ${getStatusBadge(proj.status)}
                                            <span style="margin-left: 0.5rem; font-size: 0.75rem; color: var(--text-secondary);">
                                                👤 ${proj.owner?.full_name || '未分配'}
                                            </span>
                                        </div>
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    `;
                }

                html += '</div>';
                container.innerHTML = html;
            } catch (error) {
                console.error('加载项目失败:', error);
                showNotification('加载项目失败', 'error');
            }
        }

        // 加载下属小卡片
        async function loadSubordinates() {
            try {
                const data = await getTeamStatus();
                allSubordinates = data; // 保存下属信息供创建项目时使用
                const container = document.getElementById('subordinates-container');

                if (data.length === 0) {
                    container.innerHTML = '<p style="text-align: center; color: var(--text-secondary); grid-column: 1 / -1;">暂无下属</p>';
                    return;
                }

                container.innerHTML = data.map(member => {
                    const status = member.latest_status;
                    const statusColors = {
                        on_site: 'var(--success-color)',
                        remote: 'var(--primary-color)',
                        leave: 'var(--warning-color)',
                        out: 'var(--secondary-color)'
                    };
                    const statusColor = status ? statusColors[status.work_status] : 'var(--text-secondary)';

                    return `
                        <div class="card subordinate-card" style="padding: 1rem; cursor: pointer; transition: transform 0.2s, box-shadow 0.2s;"
                             onclick="viewUserDetails(${member.user.id})"
                             onmouseover="this.style.transform='translateY(-4px)'; this.style.boxShadow='var(--shadow-lg)'"
                             onmouseout="this.style.transform=''; this.style.boxShadow='var(--shadow)'">
                            <div style="text-align: center;">
                                <div style="width: 60px; height: 60px; border-radius: 50%; background: linear-gradient(135deg, ${statusColor}, ${statusColor}99); margin: 0 auto 0.75rem; display: flex; align-items: center; justify-content: center; color: white; font-size: 1.5rem; font-weight: 700;">
                                    ${member.user.full_name.charAt(0)}
                                </div>
                                <h4 style="margin-bottom: 0.25rem; font-size: 0.95rem;">${member.user.full_name}</h4>
                                <p style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 0.5rem;">
                                    ${member.user.department || '未分配部门'}
                                </p>
                                ${status ? getStatusBadge(status.work_status) : '<span class="badge badge-secondary">无状态</span>'}
                                ${status && status.current_task ? `
                                    <p style="font-size: 0.75rem; color: var(--text-secondary); margin-top: 0.5rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                                        ${status.current_task}
                                    </p>
                                ` : ''}
                            </div>
                        </div>
                    `;
                }).join('');
            } catch (error) {
                showNotification('加载下属列表失败', 'error');
            }
        }

        // AI查询
        async function performAIQuery() {
            const input = document.getElementById('ai-query-input');
            const responseDiv = document.getElementById('ai-response');
            const responseText = document.getElementById('ai-response-text');

            if (!input.value.trim()) {
                showNotification('请输入查询内容', 'warning');
                return;
            }

            responseDiv.style.display = 'block';
            responseText.innerHTML = '<p style="text-align: center;">🤖 AI正在思考...</p>';

            try {
                const result = await aiQuery(input.value);
                // 使用Markdown渲染器格式化AI响应
                const formattedResponse = renderMarkdown(result.response);
                responseText.innerHTML = formattedResponse;
            } catch (error) {
                responseText.innerHTML = '<p style="color: var(--danger-color);">查询失败，请检查AI服务是否启动</p>';
            }
        }

        // 创建目标
        document.getElementById('create-objective-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData);

            try {
                await createObjective(data);
                showNotification('目标创建成功', 'success');
                closeModal('create-objective-modal');
                e.target.reset();
                loadObjectivesByType();
            } catch (error) {
                showNotification('创建失败: ' + error.message, 'error');
            }
        });

        // 打开编辑目标模态框
        async function openEditObjective(objectiveId) {
            try {
                const objective = await apiRequest(`/api/objectives/${objectiveId}`);

                document.getElementById('edit-objective-id').value = objective.id;
                document.getElementById('edit-objective-title').value = objective.title;
                document.getElementById('edit-objective-description').value = objective.description || '';
                document.getElementById('edit-objective-type').value = objective.type;
                document.getElementById('edit-objective-status').value = objective.status;
                document.getElementById('edit-objective-start-date').value = objective.start_date;
                document.getElementById('edit-objective-end-date').value = objective.end_date;

                openModal('edit-objective-modal');
            } catch (error) {
                showNotification('加载目标信息失败', 'error');
            }
        }

        // 编辑目标
        document.getElementById('edit-objective-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const objectiveId = parseInt(document.getElementById('edit-objective-id').value);
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData);

            try {
                await updateObjective(objectiveId, data);
                showNotification('目标更新成功', 'success');
                closeModal('edit-objective-modal');
                loadObjectivesByType();
            } catch (error) {
                showNotification('更新失败: ' + error.message, 'error');
            }
        });

        // 确认删除目标
        function confirmDeleteObjective(objectiveId) {
            if (confirm('确定要删除这个目标吗？此操作无法撤销，相关的下属目标也会受到影响。')) {
                deleteObjectiveById(objectiveId);
            }
        }

        // 删除目标
        async function deleteObjectiveById(objectiveId) {
            try {
                await deleteObjective(objectiveId);
                showNotification('目标已删除', 'success');
                loadObjectivesByType();
            } catch (error) {
                showNotification('删除失败: ' + error.message, 'error');
            }
        }

        // 打开创建项目模态框时，加载目标和下属列表
        async function openCreateProjectModal() {
            try {
                // 加载所有目标，只显示部门级别的目标
                const objectives = await getObjectives();
                const departmentObjectives = objectives.filter(obj => obj.level === 'department');

                const objSelect = document.getElementById('create-project-objective-select');
                objSelect.innerHTML = '<option value="">选择此项目服务的目标</option>';
                departmentObjectives.forEach(obj => {
                    objSelect.innerHTML += `<option value="${obj.id}">${obj.title}</option>`;
                });

                // 加载下属列表
                const ownerSelect = document.getElementById('create-project-owner-select');
                ownerSelect.innerHTML = '<option value="">选择项目负责人</option>';
                allSubordinates.forEach(sub => {
                    ownerSelect.innerHTML += `<option value="${sub.user.id}">${sub.user.full_name}</option>`;
                });

                openModal('create-project-modal');
            } catch (error) {
                showNotification('加载数据失败', 'error');
            }
        }

        // 创建项目
        document.getElementById('create-project-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData);
            const objectiveId = parseInt(data.objective_id);

            try {
                // 1. 创建项目
                const project = await createProject({
                    name: data.name,
                    description: data.description,
                    owner_id: parseInt(data.owner_id),
                    start_date: data.start_date,
                    end_date: data.end_date
                });

                // 2. 关联到目标
                if (objectiveId) {
                    await apiRequest('/api/projects/link', {
                        method: 'POST',
                        body: JSON.stringify({
                            project_id: project.id,
                            objective_id: objectiveId
                        })
                    });
                }

                showNotification('项目创建成功', 'success');
                closeModal('create-project-modal');
                e.target.reset();
                loadProjects();
            } catch (error) {
                showNotification('创建失败: ' + error.message, 'error');
            }
        });

        // 打开编辑项目模态框
        async function openEditProject(projectId) {
            try {
                const project = await apiRequest(`/api/projects/${projectId}`);

                // 填充表单
                document.getElementById('edit-project-id').value = project.id;
                document.getElementById('edit-project-name').value = project.name;
                document.getElementById('edit-project-description').value = project.description || '';
                document.getElementById('edit-project-start-date').value = project.start_date;
                document.getElementById('edit-project-end-date').value = project.end_date || '';
                document.getElementById('edit-project-progress').value = project.progress;
                document.getElementById('edit-project-status').value = project.status;

                // 加载所有目标，只显示部门级别的目标
                const objectives = await getObjectives();
                const departmentObjectives = objectives.filter(obj => obj.level === 'department');

                const objSelect = document.getElementById('edit-project-objective-select');
                objSelect.innerHTML = '<option value="">选择此项目服务的目标</option>';
                departmentObjectives.forEach(obj => {
                    objSelect.innerHTML += `<option value="${obj.id}">${obj.title}</option>`;
                });

                // 设置当前关联的目标
                const currentObjectiveId = project.linked_objectives && project.linked_objectives.length > 0
                    ? project.linked_objectives[0].objective_id
                    : null;
                if (currentObjectiveId) {
                    objSelect.value = currentObjectiveId;
                    document.getElementById('edit-project-old-objective-id').value = currentObjectiveId;
                }

                // 加载下属列表
                const ownerSelect = document.getElementById('edit-project-owner-select');
                ownerSelect.innerHTML = '<option value="">选择项目负责人</option>';
                allSubordinates.forEach(sub => {
                    ownerSelect.innerHTML += `<option value="${sub.user.id}">${sub.user.full_name}</option>`;
                });
                ownerSelect.value = project.owner_id;

                openModal('edit-project-modal');
            } catch (error) {
                showNotification('加载项目信息失败', 'error');
            }
        }

        // 编辑项目
        document.getElementById('edit-project-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const projectId = parseInt(document.getElementById('edit-project-id').value);
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData);
            const newObjectiveId = parseInt(data.objective_id);
            const oldObjectiveId = document.getElementById('edit-project-old-objective-id').value
                ? parseInt(document.getElementById('edit-project-old-objective-id').value)
                : null;

            try {
                // 1. 更新项目基本信息（包含owner_id）
                await apiRequest(`/api/projects/${projectId}`, {
                    method: 'PUT',
                    body: JSON.stringify({
                        name: data.name,
                        description: data.description,
                        start_date: data.start_date,
                        end_date: data.end_date,
                        progress: parseFloat(data.progress),
                        status: data.status,
                        owner_id: parseInt(data.owner_id)
                    })
                });

                // 2. 如果目标发生变化，更新关联关系
                if (newObjectiveId && newObjectiveId !== oldObjectiveId) {
                    // 获取完整项目信息以找到旧的关联ID
                    const project = await apiRequest(`/api/projects/${projectId}`);

                    // 删除旧关联
                    if (oldObjectiveId && project.linked_objectives) {
                        const oldLink = project.linked_objectives.find(l => l.objective_id === oldObjectiveId);
                        if (oldLink) {
                            await apiRequest(`/api/projects/link/${oldLink.id}`, { method: 'DELETE' });
                        }
                    }

                    // 创建新关联
                    await apiRequest('/api/projects/link', {
                        method: 'POST',
                        body: JSON.stringify({
                            project_id: projectId,
                            objective_id: newObjectiveId
                        })
                    });
                }

                showNotification('项目更新成功', 'success');
                closeModal('edit-project-modal');
                loadProjects();
            } catch (error) {
                showNotification('更新失败: ' + error.message, 'error');
            }
        });

        // 确认删除项目
        function confirmDeleteProject() {
            if (confirm('确定要删除这个项目吗？此操作无法撤销。')) {
                deleteProject();
            }
        }

        // 删除项目
        async function deleteProject() {
            const projectId = document.getElementById('edit-project-id').value;
            try {
                await apiRequest(`/api/projects/${projectId}`, { method: 'DELETE' });
                showNotification('项目已删除', 'success');
                closeModal('edit-project-modal');
                loadProjects();
            } catch (error) {
                showNotification('删除失败: ' + error.message, 'error');
            }
        }

        function viewUserDetails(userId) {
            window.location.href = `/auth/user/${userId}`;
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', async () => {
            // 设置语言选择器的当前值
            const savedLang = localStorage.getItem('language') || 'zh';
            document.getElementById('language-selector').value = savedLang;

            // 先加载项目数据
            allProjects = await getProjects({ include_objectives: true });

            // 然后加载其他内容
            loadObjectivesByType();
            loadProjects();
            loadSubordinates();
        });

        // 监听语言切换事件，重新加载所有动态内容
        document.addEventListener('languageChanged', () => {
            loadObjectivesByType();
            loadProjects();
            loadSubordinates();
        });
    </script>
</body>
</html>